﻿using SqlSugar;
using Wechat_PublicNumber.Entity;
using Wechat_PublicNumber.Model;
using Wechat_PublicNumber.Model.Output;

namespace Wechat_PublicNumber.Repository
{
    public class UserRepository : DataAccess
    {
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public async Task<UserInfo> GetUserInfo(long ID) => await WXDb.Queryable<UserInfo>().FirstAsync(s => s.ID == ID);


        /// <summary>
        /// 获取微信推送模板列表
        /// </summary>
        /// <param name="keyWord"></param>
        /// <param name="openID"></param>
        /// <returns></returns>
        public async Task<List<PushTemplateListOutput>> GetPushTemplateList(string keyWord, string openID)
        {
            return await WXDb.Queryable<WeChatTemplate, WeChatTemplateSet>((t, ts) => new object[]
             {
                JoinType.Left,t.ID==ts.TemplateID && ts.OpenID==openID
             })
             .Where((t, ts) => t.Type == WeChatTemplateTypeEnum.All || t.OpenID.Contains(openID))
             .WhereIF(!string.IsNullOrEmpty(keyWord), (t, ts) => t.Description == keyWord)
             .Select((t, ts) => new PushTemplateListOutput
             {
                 ID = t.ID,
                 Name = t.Description,
                 Status = SqlFunc.IF(ISNull("ts.Status")).Return(true).End(ts.Status)
             }).ToListAsync();
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="weChatTemplateSet"></param>
        /// <returns></returns>
        public async Task SaveWeChatTemplateSet(WeChatTemplateSet weChatTemplateSet)
        {
            await WXDb.SaveEntityInfo(weChatTemplateSet);
        }

        /// <summary>
        /// GetOne
        /// </summary>
        /// <param name="tempID"></param>
        /// <param name="openID"></param>
        /// <returns></returns>
        public async Task<WeChatTemplateSet> GetWeChatTemplateSet(WeChatTemplateEnum tempID, string openID)
        {
            return await WXDb.Queryable<WeChatTemplate, WeChatTemplateSet>((t, ts) => new object[]
             {
                JoinType.Inner,t.ID==ts.TemplateID
             }).Where((t, ts) => ts.TemplateID == tempID && ts.OpenID == openID)
             .Select((t, ts) => ts)
             .FirstAsync();
        }
    }
}
